<template>
    <div class="main-body">
        <div class="header">
            <el-card class="box-card">
                <el-row type="flex" class="row-bg">
                    <el-col :span="22">
                        <span style="line-height: 37px;">距离考试结束还有：</span>
                        <span style="line-height: 37px;font-weight: bold">{{countdown}}</span>
                    </el-col>
                    <el-col :span="2">
                        <div class="grid-content bg-purple-light">
                            <el-button type="primary" size="medium" style="margin-right: 20px;"
                                       icon="el-icon-edit" @click="checkTag" v-preventReClick>交卷
                            </el-button>
                        </div>
                    </el-col>
                </el-row>
            </el-card>
        </div>
        <div class="main">
            <div class="aside">
                <el-card class="box-card">
                    <div>
                        <p class="title">答题卡</p>
                        <div class="title-tag">
                            <el-tag type="success" size="medium">已作答</el-tag>
                            <el-tag type="info" size="medium">未作答</el-tag>
                        </div>
                    </div>
                    <div class="answer-tag-items">
                        <div v-for="i in 5">
                            <div v-if="groupList[i] !==undefined && groupList[i] != null  && groupList[i].length > 0">
                                <p class="title">{{ questionTypeList[i - 1]}}</p>
                                <div class="title-tag">
                                    <el-tag ref="tags" :type="changeTagType(question)" @click="jump(i,index)"
                                            size="medium"
                                            v-for="(question,index) in groupList[i]"
                                            :key="`${i} +'-'+ ${index}`" :id="`'a'+ ${i} +'-'+ ${index}`">
                                        <div>{{(groupInfoList[i-1].startIndex + index + 1)}}</div>
                                    </el-tag>
                                </div>
                            </div>
                        </div>
                    </div>
                </el-card>
            </div>
            <div class="content">
                <el-card class="box-card">
                    <div slot="header" class="clearfix">
                        <span>{{paper.paperName}}</span>
                    </div>
                    <div>
                        <div v-for="i in 5" class="question-content">
                            <div v-if="groupList[i] !==undefined && groupList[i] != null  && groupList[i].length > 0">
                                <div>
                                    <span class="questionType">{{ questionTypeList[i - 1]}}</span>
                                    <span class="question-score">{{'（共'+groupInfoList[i-1].count+'题，'+groupInfoList[i-1].scoreSum+'分）'}}
                                        </span>
                                </div>

                                <div v-for="(question,index) in groupList[i]" :id="`${i}-${index}`" class="question">
                                    <el-row>
                                        <el-col :span="0.5">
                                        </el-col>
                                        <el-col :span="0.5">
                                            <div>{{(groupInfoList[i-1].startIndex + index + 1) + "."}}</div>

                                        </el-col>
                                        <el-col :span="23">
                                            <div class="question-title">
                                                <span class="question-content"
                                                      v-html="handleContentHTML(question.questionTitle)"></span>
                                                <span class="score">{{ questionTypeList[i - 1]+' ' + question.score+'分'}}</span>
                                            </div>
                                            <div v-if="question.questionType == 1">
                                                <div class="option">
                                                    <el-radio-group v-model="form[question.questionId]" size="medium">
                                                        <el-radio label="A" border>A. {{question.optionA}}</el-radio>
                                                        <el-radio label="B" border>B. {{question.optionB}}</el-radio>
                                                        <el-radio label="C" border>C. {{question.optionC}}</el-radio>
                                                        <el-radio label="D" border>D. {{question.optionD}}</el-radio>
                                                    </el-radio-group>
                                                </div>
                                            </div>
                                            <div v-if="question.questionType == 2">
                                                <div class="option">
                                                    <el-checkbox-group v-model="form[question.questionId]"
                                                                       size="medium">
                                                        <el-checkbox label="A" border>A. {{question.optionA}}
                                                        </el-checkbox>
                                                        <el-checkbox label="B" border>B. {{question.optionB}}
                                                        </el-checkbox>
                                                        <el-checkbox label="C" border>C. {{question.optionC}}
                                                        </el-checkbox>
                                                        <el-checkbox label="D" border>D. {{question.optionD}}
                                                        </el-checkbox>
                                                    </el-checkbox-group>
                                                </div>
                                            </div>
                                            <div v-if="question.questionType == 3">
                                                <div class="option">
                                                    <el-radio-group v-model="form[question.questionId]" size="medium">
                                                        <el-radio label="A" border>{{question.optionA}}</el-radio>
                                                        <el-radio label="B" border>{{question.optionB}}</el-radio>
                                                    </el-radio-group>
                                                </div>
                                            </div>
                                            <div v-if="question.questionType == 4">
                                                <div class="option">
                                                    <el-input placeholder="请输入答案" v-model="form[question.questionId]"
                                                              size="medium">
                                                        <template slot="prepend">填写答案</template>
                                                    </el-input>
                                                </div>
                                            </div>
                                            <div v-if="question.questionType == 5">
                                                <div class="option">
                                                    <el-input type="textarea" size="medium" rows="5" placeholder="请输入答案"
                                                              v-model="form[question.questionId]">
                                                    </el-input>
                                                </div>
                                            </div>
                                        </el-col>
                                    </el-row>
                                </div>
                            </div>
                        </div>
                    </div>
                </el-card>
            </div>
        </div>
        <el-dialog
                title="提示"
                :visible.sync="checkTagDialogVisible"
                width="30%"
                :before-close="handleClose">
            <span>还有题目没完成，是否结束考试</span>
            <span slot="footer" class="dialog-footer">
    <el-button @click="checkTagDialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="submitPaper">确 定</el-button>
  </span>
        </el-dialog>
        <el-backtop target=".content"></el-backtop>
    </div>
</template>
<style>
    /*@import "../assets/css/do.css";*/
    .header {
        width: 100%;
        /*不生效*/
        height: 75px;
        position: fixed;
        border-bottom: 1px solid #e4e6e9;
        /*以下自定义样式*/
        top: 10px;
        padding-left: 12px;
        padding-right: 12px;
    }

    .aside {
        position: fixed;
        top: 100px;
        bottom: 0;
        left: 0;
        width: 25%;
        /*以下自定义样式*/
        padding-left: 12px;
        padding-right: 12px;
    }

    .content {
        position: fixed;
        top: 100px;
        right: 0;
        bottom: 0;
        left: 25%;
        overflow-y: auto;
        /*以下自定义样式*/
        padding-left: 12px;
        padding-right: 12px;
    }
    .content .el-card__body{
        padding-top:0;
    }
    /*美化单选框*/
    .option{
        margin-top: 10px;
        width: 100%;
    }
    .option .el-radio{
        display: inline-block;
        width: 100%;
        margin-left: 10px;
        margin-bottom: 10px;
    }
    .option .el-radio-group label{
        /*width: 550%;*/
    }
    .el-radio__input{
        display: none;
    }


    /*美化多选框*/
    .option .el-checkbox{
        display: inline-block;
        width: 100%;
        margin-left: 10px;
        margin-bottom: 10px;
    }
    .option .el-checkbox-group label{
        /*width: 550%;*/
    }
    .el-checkbox__input{
        display: none;
    }

    .title {
        background: #eee;
        line-height: 35px;
        text-align: center;
        font-size: 14px;
    }

    .title-tag {
        margin-left: -12px;
        margin-right: -12px;
        padding-left: 10px;
    }

    .title-tag .el-tag {
        cursor: pointer;
        margin: 10px 2px;
    }

    .questionType{
        line-height: 60px;
        font-size: 16px;
        font-weight: bold;
    }
    .question-score{
        color: #949494;
        margin-left: 6px;
        font-size: 12px;
    }
    .question{
        margin-top: 10px;
        padding-bottom: 10px;
        border-bottom: 1px solid #dedede;
    }

    .question-title .score{
        font-size: 12px;
        background-color: #f4f4f4;
        border-radius: 15px;
        padding: 2px 8px;
        color: #9d9d9d;
        margin-right: 6px;
        display: inline-block;
    }
</style>
<script>

    import request from "../utils/request";
    import {serverIp} from "../../public/config";
    import {setRoutes} from "../router";

    export default {
        name: 'Do',
        components: {},
        data() {
            return {
                form: {},
                paper: {},
                user:{},
                groupList: [],
                groupInfoList: [],//存储分组题目的题目总数量和总分值
                checkTagDialogVisible: false,
                time: 60,
                countdown: '加载中',
                checkboxList: {},
                questionTypeList: ['单选题', '多选题', '判断题', '填空题', '客观题'],
            }
        },
        created() {
            this.getUser();
            this.load()
            // this.setPaper();
            console.log("request.paper", this.paper)
            this.preprocessData();
            console.log("checklist:", this.checkboxList)
            this.showTime();
        },
        mounted() {
            history.pushState(null, null, document.URL);
            window.addEventListener('popstate', function () {
                history.pushState(null, null, document.URL);
            });
        },
        methods: {
            load() {
                //处理结束参数
                if (this.$route.params.paper) {
                    this.paper = this.$route.params.paper;
                    console.log("paper", this.paper)
                } else {
                    this.$message.error("参加考试异常");
                }
            },
            getUser() {
                this.user = localStorage.getItem("user") ? JSON.parse(localStorage.getItem("user")):{}
                if (!this.user) {
                    this.$message.info("获取用户失败，请重新登录")
                }
            },
            async preprocessData() {
                if (this.paper["makePaperMethod"] == 2) {
                    //获取随机试卷
                    await request.post('/question/randomPaper', this.paper).then(res => {
                        console.log("code:", res.code)
                        if (res.code == '200') {
                            this.paper["questionList"] = res.data;
                            console.log('this.form.questionList', this.paper["questionList"])
                            //修改随机组卷分值
                            //随机组卷，修改题目分值
                            this.paper["questionList"].forEach((item,index,arr) => {
                                //填补没有作答的题目
                                if (item.questionType == 1) {
                                    item.score = this.paper.radioScore
                                }
                                if (item.questionType == 2) {
                                    item.score = this.paper.checkboxScore
                                }
                                if (item.questionType == 3) {
                                    item.score = this.paper.judgeScore
                                }
                            })

                        } else {
                            this.$message.error("获取试卷失败")
                        }
                    })
                }else{
                    //获取固定试卷
                    await request.post('/paper/findPaperByPaperId', this.paper).then(res => {
                        console.log("code:", res.code)
                        if (res.code == '200') {
                            this.paper = res.data;
                            console.log('this.form.questionList', this.paper["questionList"])
                        }
                    })
                }
                //根据题型分类
                //1.数组初始化
                for (let i = 1; i < 6; i++) {
                    this.groupList[i] = [];//数组初始化
                }
                console.log("groupList", this.groupList)
                //2.按题目类型，把questionList分为groupList，数据分组
                for (const question of this.paper["questionList"]) {
                    this.groupList[question.questionType].push(question);
                }
                console.log("questionList",this.paper["questionList"])

                console.log("groupList", this.groupList)

                //统计题目,存储分组题目的题目总数量和总分值
                let i = 0;//题目类别
                let startIndex = 0;//题目起始序号
                let count = 0;
                for (let k = 1; k < 6; k++) {
                    let scoreSum = 0;
                    this.groupList[k].forEach(question => {
                        scoreSum += question.score;
                    })
                    if (scoreSum != 0) {
                        i++;
                    }
                    count = this.groupList[k].length;
                    this.groupInfoList.push({'i': i, 'startIndex': startIndex, 'count': count, 'scoreSum': scoreSum});
                    startIndex += count;//是上一种题型的累计
                }

                //单独对多选题突出
                this.groupList[2].forEach(question => {
                    console.log("question", question)
                    this.$set(this.form, question.questionId, [])
                })
                //输出处理结果
                console.log("groupInfo:", this.groupInfoList)
                console.log("form:", this.form)
                console.log("groupList", this.groupList)
            },
            changeTagType(question) {
                if (this.form[question.questionId] == null || this.form[question.questionId] == undefined || this.form[question.questionId].length <= 0) {
                    return "info";
                } else {
                    return "success";
                }
            },
            showTime() {
                this.time = this.paper.suggestTime * 60;//秒
                let time = setInterval(() => {
                    this.time--;
                    let h = parseInt(this.time / 60 / 60 % 24)
                    h = h < 10 ? '0' + h : h
                    let m = parseInt(this.time / 60 % 60)
                    m = m < 10 ? '0' + m : m
                    let s = parseInt(this.time % 60)
                    s = s < 10 ? '0' + s : s
                    this.countdown = "";
                    if (h != "00") {
                        this.countdown += h + "时"
                    }
                    if (m != "00") {
                        this.countdown += m + "分"
                    }
                    this.countdown += s + "秒"
                    //处理考试时间结束
                    if (this.time < 0) {
                        this.submitPaper();//提交试卷
                        this.countdown = "考试结束";
                        clearInterval(time);
                    }
                }, 1000)
            },
            checkTag() {
                let tags = this.$refs.tags;
                let flag = true;//默认提交试卷
                for (let i = 0; i < tags.length; i++) {
                    if (tags[i].type == "info") {
                        flag = false;//不符合提交要求
                        this.checkTagDialogVisible = true;
                        break;
                    }
                }
                if (flag) {
                    this.submitPaper();//提交试卷
                }

            },
            submitPaper() {
                this.checkTagDialogVisible = false;//关闭对话框
                //需要修改studentId,有问题
                let studentId = this.user.userId;
                for (const question of this.paper["questionList"]) {
                    this.form[question.questionId] = this.form[question.questionId] || ""; //填补没有作答的题目
                }
                //封装答案
                let doTime = this.paper.suggestTime * 60 - this.time;
                console.log("doTime", doTime)
                console.log("form:", this.form)
                let answerList = [];
                Object.keys(this.form).forEach((key, value) => {
                    //处理不同类型的答案
                    let answer = null;
                    //多选题答案处理
                    if (this.form[key] instanceof Array) {
                        answer = JSON.stringify(this.form[key].sort());
                    } else {
                        answer = this.form[key];
                    }
                    //随机试卷设置题目分值
                    let question = this.searchByquestionId(key)
                    let questionScore = question.score;
                    console.log("key:", key, "question:", question)
                    if (this.paper["makePaperMethod"] == 2) { //随机组卷，修改题目分值
                        if (question.questionType == 1) {
                            questionScore = this.paper.radioScore
                        }
                        if (question.questionType == 2) {
                            questionScore = this.paper.checkboxScore
                        }
                        if (question.questionType == 3) {
                            questionScore = this.paper.judgeScore
                        }
                    }

                    console.log("score", questionScore)
                    answerList.push({
                        'paperId': this.paper.paperId,
                        'questionId': parseInt(key),
                        'studentId': studentId,
                        'answer': answer,
                        'questionScore': questionScore,
                        'createTime': new Date(),
                        'doTime': doTime
                    })
                })
                console.log("answerList:", answerList)
                request.post('/answer/saveList', answerList).then(res => {
                    console.log("code:", res.code)
                    if (res.code == '200') {
                        this.$message.success("交卷成功")
                        //跳转到其他页面
                        console.log("考试结果", res.data)
                        this.$router.push({
                            path: "/exam/result", name: 'Result', params: {
                                examInfo: res.data,
                                text:"考试结束",
                                rollback:"/exam"
                            }
                        });


                    } else {
                        this.$message.error("交卷失败")
                    }
                }).catch((err) => {
                    this.$message.error(err);
                })
            },
            jump(i, index) {
                //点击答题卡，跳转到对应题目
                document.getElementById(i + "-" + index).scrollIntoView();
            },
            handleContentHTML(content) {
                return content.slice(3, -4);
            },
            handleClose() {
                this.checkTagDialogVisible = false;
            },
            searchByquestionId(questionId) {
                let question = this.paper.questionList.find(item => {
                    return item.questionId == questionId
                })
                console.log("找到了", question)
                return question;


            },
            setPaper() {
                this.paper = {
                    "paperId": 151,
                    "paperName": "数学分析考试1",
                    "score": "2",
                    "courseId": "3",
                    "courseName": "数学分析",
                    "questionCount": null,
                    "radioQuestionCount": 4,
                    "checkboxQuestionCount": 3,
                    "judgeQuestionCount": 1,
                    "fillQuestionCount": null,
                    "objectiveQuestionCount": null,
                    "suggestTime": 8,
                    "limitStartTime": null,
                    "limitEndTime": null,
                    "address": null,
                    "teacherId": "1",
                    "teacherName": "王一",
                    "createTime": "2022-04-15T16:04:46.000+00:00",
                    "paperType": 1,
                    "difficult": 3,
                    "makePaperMethod": 2,
                    "radioScore": 20,
                    "checkboxScore": 10,
                    "judgeScore": 5,
                    "questionList": null,
                    "useStatus": "1"
                };

            }


        }

    }
</script>
